package cn.wolfcode.crm.util;

import com.alibaba.fastjson.JSONObject;

import java.util.Date;

public class WeChatUtil {
    public static final String TOKEN = "xiaolin";
    public static final String APPID = "wx3c5a942272e2c02a";
    public static final String APPSECRET = "ebb46d7bc7882eb8f9a015de3b043bed";

    // 创建菜单接口
    public static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    // 获取普通accessToken接口
    public static final String GET_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    // 调用各个接口的凭据
    public static String accessToken;

    // 凭据的失效时间
    public static Long expiresTime;

    /**
     * 获取AccessToken凭据
     * @return
     */
    public static String getAccessToken(){
        if (accessToken==null || expiresTime > new Date().getTime()){
            String result = HttpRequest.sendGet(GET_ACCESSTOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET));
            JSONObject json = JSONObject.parseObject(result);
            // 凭据
            accessToken = json.getString("access_token");
            // 有效期
            Long expires_in = json.getLong("expires_in");
            expiresTime = new Date().getTime() + ((expires_in-60) * 1000);
            System.out.println(result);
        }
        return accessToken;
    }

    /**
     * 创建菜单
     */
    public static void createMenu(String menuJson){
        String result = HttpRequest.sendPost(CREATE_MENU_URL.replace("ACCESS_TOKEN",getAccessToken()),menuJson);
        System.out.println(result);
    }

    public static void main(String[] args) {
        createMenu("{\n" +
                "    \"botton\":[\n" +
                "    {\n" +
                "        \"type\":\"click\",\n" +
                "        \"name\":\"开学信息\",\n" +
                "        \"key\":\"classinfo\"\n" +
                "    }，\n" +
                "    {\n" +
                "        \"type\":\"click\",\n" +
                "        \"name\":\"校区地址\",\n" +
                "        \"key\":\"address\"\n" +
                "    },\n" +
                "    {\n" +
                "        \"name\":\"学科介绍\",\n" +
                "        \"sub_button\":[\n" +
                "        {\n" +
                "         \t\"type\":\"view\",\n" +
                "            \"name\":\"java课程\",\n" +
                "            \"url\":\"https://www.wolfcode.cn/java.html\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"type\":\"view\",\n" +
                "            \"name\":\"Python课程\",\n" +
                "            \"url\":\"https://www.wolfcode.cn/python.html\"\n" +
                "        }]\n" +
                "    }]\n" +
                "}");
    }
}
